const wxCharts = require('../../utils/wxcharts-min.js');
import api from '../../api/api'
import { urlObj } from '../../api/url'
const app = getApp()
let lineChart = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canvasHidden:false,
    params: {},
    deviceDetail: {},
    chartData: {},
    iserror: {
      "03": '运行正常',
      "04": '无效数据',
      "11": '电缆温度异常',
      "22": '环境温湿度异常'
    },
    pageOption: {},
    showRoutePlan:false,
    showTypes:[],
    buttons: [{text: '取消'}, {text: '确定'}],
    dialogShow:false,
    phoneString:'',
    conLists: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    console.log(options.hasOwnProperty('name'))
    this.setData({
      pageOption: options,
      showRoutePlan:options.hasOwnProperty('name')
    })
    this.getDeviceDetail(options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getBarChartData(this.data.pageOption.id)
  },
  // 获取设备详情
  getDeviceDetail(id) {
    const params = {
      deviceId: id
    }
    wx.showLoading({
      title: '加载中...',
    })
    api.get(urlObj.deviceDetail, params).then(res => {
      wx.hideLoading()
      if (res.statusCode == '200') {
        let { data } = res;
        for( let key in data) {
          if(key == 'earlyWarning' || key == 'callWarning'){
            data[key] = parseInt(data[key])/10 || '无'
          } else if(key.indexOf('temperature') >= 0 || key.indexOf('humidity') >= 0 || key.indexOf('voltage') >= 0){
            data[key] = parseInt(data[key])/10  || '0'
          } else {
            data[key] = data[key]  || '0'
          }
        }
        this.setData({
          deviceDetail: data,
          showTypes:data.showType == '0' ? [] : data.showType.split(',')
        })
        console.log(this.data.showTypes)
      }
    })
  },
  getBarChartData(id) {
    const params = {
      deviceId: id
    }
    api.get(urlObj.getChartData, params).then(res => {
      if (res.statusCode == '200') {
        let { data } = res;
        let targetItem = data.resData.result.data.items;
        // 异常处理
        if(!targetItem) {
          return false
        }
        let cate = targetItem.map(item => {
          return (item.createtime.split(' ')[1])
        })
        let acurrentData = targetItem.map(item => {
          return parseInt(item.acurrent)/10
        })
        let bcurrentData = targetItem.map(item => {
          return parseInt(item.bcurrent)/10
        })
        let ccurrentData = targetItem.map(item => {
          return parseInt(item.ccurrent)/10
        })
        let avoltageData = targetItem.map(item => {
          return parseInt(item.avoltage)/10
        })
        let bvoltageData = targetItem.map(item => {
          return parseInt(item.bvoltage)/10
        })
        let cvoltageData = targetItem.map(item => {
          return parseInt(item.cvoltage)/10
        })
        let atemperatureData = targetItem.map(item => {
          return parseInt(item.atemperature)/10
        })
        let btemperatureData = targetItem.map(item => {
          return parseInt(item.btemperature)/10
        })
        let ctemperatureData = targetItem.map(item => {
          return parseInt(item.ctemperature)/10
        })
        const option1 = {
          dataCate: ['A相电流', 'B相电流', 'C相电流'],
          categories: cate,
          data1: acurrentData,
          data2: bcurrentData,
          data3: ccurrentData,
        }
        const option2 = {
          dataCate: ['A电缆电压', 'B电缆电压', 'C电缆电压'],
          categories: cate,
          data1: avoltageData,
          data2: bvoltageData,
          data3: cvoltageData,
        }
        const option3 = {
          dataCate: ['A电缆温度', 'B电缆温度', 'C电缆温度'],
          categories: cate,
          data1: atemperatureData,
          data2: btemperatureData,
          data3: ctemperatureData,
        }
        this.drawAnchart('lineCanvas', option1)
        this.drawAnchart('lineCanvas2', option2)
        this.drawAnchart('lineCanvas3', option3)
      }
    })
  },
  //初始化图表
  drawAnchart(id, options) {
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
    new wxCharts({
      canvasId: id,
      type: 'line',
      categories: options.categories,
      animation: true,
      background: '#f5f5f5',
      series: [{
        name: options.dataCate[0],
        data: options.data1,
        format: function (val, name) {
          return val.toFixed(2);
        }
      }, {
        name: options.dataCate[1],
        data: options.data2,
        format: function (val, name) {
          return val.toFixed(2);
        }
      }, {
        name: options.dataCate[2],
        data: options.data3,
        format: function (val, name) {
          return val.toFixed(2);
        }
      }],
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        show: false,
        title: '',//y轴标题
        format: function (val) {
          return val.toFixed(2);
        },
        min: 0
      },
      width: windowWidth,
      height: 200,
      dataLabel: false,
      dataPointShape: true,
      extra: {
        lineStyle: 'curve'
      }
    });
  },
  tapHere() {
    if(this.data.pageOption.latitude) {
      this.handleRoutePlan(this.data.pageOption)
    } else {
      let routeParams = {
        name:this.data.deviceDetail.devicename,
        latitude: this.data.deviceDetail.latitude,
        longitude: this.data.deviceDetail.longitude,
      }
      this.handleRoutePlan(routeParams)
    }
  },
  handleRoutePlan(params) {
    console.log(params)
    //跳转腾讯地图小程序的路线规划  （v1）
    let plugin = requirePlugin('routePlan');
    let key = 'PEABZ-SMB63-L423H-YNJ44-M6Q67-LKFJW';
    let referer = '小程序专用';
    let endPoint = JSON.stringify({  //终点
      'name': params.name,
      'latitude': params.latitude,
      'longitude': params.longitude
    });
    wx.navigateTo({
      url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint
    });
  },
  // 添加手机号
  tapDialogButton(e) {
    console.log(e)
    var _conLists = this.data.conLists;
    let text = e.detail.item.text;
    if(text === '取消') {
      this.setData({
        dialogShow:false,
        canvasHidden:false
      })
    } else {
      // 验证输入的手机号
      if(_conLists.length >= 1){
        let myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
        let flag = false,falgNull = false;
        _conLists.forEach(item => {
          if(item.phone == '') {
            falgNull = true;
          }
          if(!myreg.test(item.phone)){
            flag = true
          }
        })
        if(falgNull) {
          wx.showToast({
            icon: 'none',
            title: '请输入手机号'
          })
          return false
        }
        if(flag) {
          wx.showToast({
            icon: 'none',
            title: '请输入正确的手机号'
          })
          return false
        }
      }
      let telString =  '';
      if(_conLists.length > 1) {
        _conLists.forEach((item, index) => {
          if(index !== (_conLists.length - 1)){
            telString += item.phone + ','
          }else {
            telString += item.phone
          }
        })
      }else {
        _conLists.forEach(item => {
          telString += item.phone
        })
      }
     
      const params = {
        deviceId:this.data.pageOption.id,
        tel:telString || ''
      }
      api.get(urlObj.addPhone,params).then(res => {
        console.log('2')
        this.setData({
          dialogShow: false,
          canvasHidden: false
      })
        if(res.statusCode == '200') {
          wx.showToast({
            icon:'none',
            title: '添加成功',
          })
          this.getDeviceDetail(this.data.pageOption.id)
        }else{
          wx.showToast({
            icon:'none',
            title: res.msg,
          })
        }
      }).catch(err => {
        console.log(err)
        this.setData({
            dialogShow: false,
            canvasHidden: false
        })
      })
    }
  },
  openConfirm: function () {
    let targetList = [];
    console.log(this.data.deviceDetail.noticeMember)
    let noticeMember = this.data.deviceDetail.noticeMember || '';
    if( noticeMember && noticeMember.length > 0) {
      if(noticeMember.indexOf(',') > 0) {
        let arr = noticeMember.split(',');
        arr.forEach(item => {
          if(item !== '') {
            targetList.push( {
              phone: item
            })
          }
        })
      }else{
        if(noticeMember == 0) {
          noticeMember = ''
        }
        targetList = [{phone:noticeMember}]
      }
    }else{
      console.log(targeList)
      targetList = [{phone:''}]
    }
    console.log(targetList)
    this.setData({
      conLists:targetList,
      dialogShow: true,
      canvasHidden: true
    })
    if(targetList.length == 0) {
      this.add()
    }
  },
  /**
 * 添加内容
 */
add(e) {
  // 点击添加按钮，就往数组里添加一条空数据
  var _list = this.data.conLists;
  if(this.data.conLists.length == 5) {
    wx.showToast({
      icon:'none',
      title: '只能添加5条',
    })
    return false
  }
  _list.push({phone:''})
  this.setData({
    conLists: _list
  })
},

/**
 * 删除内容
 */
del(e) {
  var idx = e.currentTarget.dataset.index;
  var _list = this.data.conLists;
  console.log(idx)
  for (let i = 0; i < _list.length; i++) {
    if (idx == i) {
      _list.splice(idx, 1)
    }
  }
  this.setData({
    conLists: _list
  })
},

/**
* 获取输入的内容标题
*/
changeConTitle(e) {
  var idx = e.currentTarget.dataset.index; //当前下标
  var val = e.detail.value; //当前输入的值
  var _list = this.data.conLists; //data中存放的数据
  for (let i = 0; i < _list.length; i++) {
    if (idx == i) {
      _list[i] = { phone: val } //将当前输入的值放到数组中对应的位置
    }
  }
  this.setData({
    conLists: _list
  })
  },
  viewMore(){
    wx.navigateTo({
      url: `../detail/moreDetail?imei=${this.data.deviceDetail.imei}`
    })
  }
})